import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';

class AutoScrollingInfiniteList extends StatefulWidget {
  const AutoScrollingInfiniteList({Key? key}) : super(key: key);

  @override
  State<AutoScrollingInfiniteList> createState() =>
      _AutoScrollingInfiniteListState();
}

class _AutoScrollingInfiniteListState extends State<AutoScrollingInfiniteList> {
  final List<int> items = List.generate(10000, (index) => index);
  final ScrollController _scrollController = ScrollController();
  Timer? _scrollTimer;
  Timer? _memoryTimer;

  static const double itemHeight = 88.0;

  @override
  void initState() {
    super.initState();

    // 滚动任务
    _scrollTimer =
        Timer.periodic(const Duration(milliseconds: 16), (timer) {
      if (!_scrollController.hasClients) return;
      final currentOffset = _scrollController.offset;
      final maxOffset = _scrollController.position.maxScrollExtent;
      final nextOffset = (currentOffset + itemHeight).clamp(0.0, maxOffset);
      _scrollController.jumpTo(nextOffset);
    });

    // 内存监控任务
    _memoryTimer =
        Timer.periodic(const Duration(seconds: 1), (timer) {
      _logMemoryUsage();
    });
  }

  void _logMemoryUsage() {
    final rssMB = ProcessInfo.currentRss / (1024 * 1024);
    debugPrint('🧠 Memory (RSS): ${rssMB.toStringAsFixed(2)} MB');
  }

  @override
  void dispose() {
    _scrollTimer?.cancel();
    _memoryTimer?.cancel();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        controller: _scrollController,
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Container(
            height: 80,
            margin: const EdgeInsets.all(4),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey.shade700),
            ),
            alignment: Alignment.center,
            child: Text("Item $index"),
          );
        },
      ),
    );
  }
}
